package com.hy.security.filter;

import com.alibaba.fastjson2.JSONObject;
import com.hy.common.base.RespResult;
import com.hy.common.base.RespResultCode;
import com.hy.common.consts.CommonConst;
import com.hy.common.consts.RedisConst;
import com.hy.entity.vo.HyUserVO;
import com.hy.security.security.TokenHandler;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;


import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 授权
 */
public class TokenAuthorizationFilter extends BasicAuthenticationFilter {

    private TokenHandler tokenHandler;
    private RedisTemplate redisTemplate;

    //构造函数
    public TokenAuthorizationFilter(AuthenticationManager authenticationManager,TokenHandler tokenHandler,RedisTemplate redisTemplate) {
        //必须调用父类的BasicAuthenticationFilter方法
        super(authenticationManager);
        this.tokenHandler = tokenHandler;
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException ,RuntimeException {
       //获取当前认证成功用户权限信息

        UsernamePasswordAuthenticationToken authRequest = getAuthentication(request);
        response.setContentType("application/json;charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        //判断如果有权限信息，放到权限上下文中
        if(authRequest != null) {
            if (authRequest.getPrincipal() != null) {
                SecurityContextHolder.getContext().setAuthentication(authRequest);
                chain.doFilter(request, response);
            } else {
                response.getWriter().write(JSONObject.toJSONString(RespResult.getInstance(RespResultCode.NO_User)));
                response.getWriter().flush();
                response.getWriter().close();
            }
        }else {
            response.getWriter().write(JSONObject.toJSONString(RespResult.getInstance(RespResultCode.NO_User)));
            response.getWriter().flush();
            response.getWriter().close();
        }
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        //从header获取token
        String token = request.getHeader("Authorization");
        if(token != null) {
            //从token获取用户名
            String username = tokenHandler.getUserInfoFromToken(token);
            //从redis获取对应权限列表
            Set<String> permissionValueList = (HashSet<String>)redisTemplate.opsForValue().get(RedisConst.PERMISSION_INFO+username);
            HyUserVO userVO = (HyUserVO) redisTemplate.opsForValue().get(RedisConst.USER_INFO + username);
            Collection<GrantedAuthority> authority = new ArrayList<>();
            if (permissionValueList!=null){
                Iterator<String> iterator = permissionValueList.iterator();
                while(iterator.hasNext()){
                    String permissionValue = iterator.next();
                    SimpleGrantedAuthority auth = new SimpleGrantedAuthority(permissionValue);
                    authority.add(auth);
                }
            }

//            for(String permissionValue : permissionValueList) {
//                SimpleGrantedAuthority auth = new SimpleGrantedAuthority(permissionValue);
//                authority.add(auth);
//            }
            return new UsernamePasswordAuthenticationToken(userVO,token,authority);
        }else {
            String token1 = request.getParameter("token");
            if (token1!=null){
                //从token获取用户名
                String username = tokenHandler.getUserInfoFromToken(token);
                //从redis获取对应权限列表
                Set<String> permissionValueList = (HashSet<String>)redisTemplate.opsForValue().get(RedisConst.PERMISSION_INFO+username);
                HyUserVO userVO = (HyUserVO) redisTemplate.opsForValue().get(RedisConst.USER_INFO + username);
                Collection<GrantedAuthority> authority = new ArrayList<>();
                if (permissionValueList!=null){
                    Iterator<String> iterator = permissionValueList.iterator();
                    while(iterator.hasNext()){
                        String permissionValue = iterator.next();
                        SimpleGrantedAuthority auth = new SimpleGrantedAuthority(permissionValue);
                        authority.add(auth);
                    }
                }

//            for(String permissionValue : permissionValueList) {
//                SimpleGrantedAuthority auth = new SimpleGrantedAuthority(permissionValue);
//                authority.add(auth);
//            }
                return new UsernamePasswordAuthenticationToken(userVO,token,authority);
            }


        }
        return null;
    }
}
